package com.example.blog.controller;

import com.example.blog.model.Article;
import com.example.blog.model.Remark;
import com.example.blog.model.Userinfo;
import com.example.blog.model.Vo.RemarkVo;
import com.example.blog.service.ArticleService;
import com.example.blog.service.RemarkService;
import com.example.blog.util.AjaxResult;
import com.example.blog.util.SessionUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author xia
 * @date Created in
 * 2023/7/11
 * 16:13
 */
@RestController
@RequestMapping("/remark")
public class RemarkController {
    @Autowired
    private RemarkService remarkService;
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/list")
    public AjaxResult getList(Integer aid){
        //1 参数检验
        if(aid==null||aid<=0){
            return AjaxResult.fail(-1,"参数有误");
        }
        //2 查询数据库
        List<RemarkVo> list=remarkService.getList(aid);
        return AjaxResult.succ(list);
    }

    //添加评论
    @RequestMapping("/add")
    public AjaxResult add(Remark remark, HttpServletRequest request){
        //1 参数检验
        if(remark==null||remark.getAid()<=0){
            return AjaxResult.fail(-1,"参数有误");
        }
        Userinfo userinfo= SessionUtil.getUser(request);
        if(userinfo==null||userinfo.getUid()<=0){
            return AjaxResult.fail(-2,"请先登录");
        }
        remark.setUid(userinfo.getUid());
        int result=remarkService.add(remark);
        return AjaxResult.succ(result);
    }

    //删除评论
    @RequestMapping("/del")
    public AjaxResult del(Integer rid,Integer aid,HttpServletRequest request){
        if(rid==null||rid<=0||aid==null||aid<=0){
            return AjaxResult.fail(-1,"参数有误");
        }
        Userinfo userinfo=SessionUtil.getUser(request);
        if(userinfo==null||userinfo.getUid()<=0){
            return AjaxResult.fail(-2,"请先登录");
        }
        Article article=articleService.getArticleByAid(aid);
        if(article==null||article.getAid()<=0){
            return AjaxResult.fail(-3,"参数有误");
        }
        if(article.getUid()!=userinfo.getUid()){
            return AjaxResult.fail(-4,"无权删除");
        }
        int result=remarkService.del(rid);
        return AjaxResult.succ(result);
    }
}
